/*
 * which.scala
 */

package acorn.jash.commands

import acorn.jash.{Cmd, Path}

import java.io.File

class which extends Cmd {
  override def exec {
    if (args == Nil) {
      err putln ("Usage: which COMMAND")
    }
    else {
      for (arg <- args) if (!find(arg))
        out putln (arg + ": not found.")
    }
  }

  private def find(arg:String) = {
    var found = false
    val paths = System.getenv("PATH").split(Path.separator)
    for (path <- paths; ext <- List("", ".exe", ".bat")) {
      val p = path + (if (path endsWith (Path.fileSeparator)) ""
                      else Path.fileSeparator) + arg + ext
      val file = new File(p)
      if (file exists) {out putln (Path winp p); found = true}
    }
    found
  }
}
